package com.uusee.framework.web.struts2.interceptor;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.uusee.util.StringUtils;

public class IPSecurityInterceptor implements Interceptor {
	private Set<String> permitIPSet = new HashSet<String>();

	/**
	 * 拦截Action的动作
	 * 
	 * @param invocation the current action invocation
	 * @return the method's return value, or null after setting HttpServletResponse.SC_FORBIDDEN
	 * @throws Exception when setting the error on the response fails
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();

		if (checkIP(request)) {
			return invocation.invoke();
		}

		HttpServletResponse response = ServletActionContext.getResponse();
		handleProhibited(request, response);
		return null;
	}
	
	private boolean checkIP(HttpServletRequest req) {
		String ip = req.getRemoteAddr();
		boolean isPermit = true;
		if ( !permitIPSet.isEmpty() && !permitIPSet.contains(ip)) {
			isPermit = false;
		} 
		return isPermit;
	}
	
	private void handleProhibited(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String reqType = request.getParameter("reqType");
		if ( StringUtils.isNotEmpty(reqType) && reqType.equals("ajax") ) {
			response.getWriter().print("403");
		} else if ( StringUtils.isNotEmpty(reqType) && reqType.equals("json") ) {
			response.setContentType("application/json");
			response.getWriter().print("{\"status\",\"403\"}");
	    } else if ( StringUtils.isNotEmpty(reqType) && reqType.equals("script") ) {
	    	response.setContentType("application/x-javascript");
			response.getWriter().print("alert('访问禁止!')");
	    } else {
			response.sendError(403);
		}
	}

	public void setPermitIPSet(Set<String> permitIPSet) {
		this.permitIPSet = permitIPSet;
	}

	/**
	 * This method currently does nothing.
	 */
	public void destroy() {
	}

	/**
	 * This method currently does nothing.
	 */
	public void init() {
	}

}
